package raft

import "fmt"
// RequestVoteArgs 是 RequestVote RPC 的参数
type RequestVoteArgs struct {
    Term         int
    CandidateID  int
    LastLogIndex int
    LastLogTerm  int
}

// RequestVoteReply 是 RequestVote RPC 的回复
type RequestVoteReply struct {
    Term        int
    VoteGranted bool
}

// RequestVote 处理 RequestVote RPC 请求
func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) error {
    rf.mu.Lock()
    defer rf.mu.Unlock()

    if args.Term > rf.currentTerm {
        rf.convertToFollower(args.Term)
    }

    if (rf.votedFor == -1 || rf.votedFor == args.CandidateID) && args.Term >= rf.currentTerm {
        rf.votedFor = args.CandidateID
        reply.VoteGranted = true
    } else {
        reply.VoteGranted = false
    }

    reply.Term = rf.currentTerm
    return nil
}

// sendRequestVote 发送 RequestVote RPC 请求
func (rf *Raft) sendRequestVote(peer *PeerClient, args *RequestVoteArgs, reply *RequestVoteReply) bool {
	if peer == nil {
        return false
    }
    err := peer.Node.RequestVote(args, reply)
    if err != nil {
        fmt.Println("RequestVote RPC failed:", err)
        return false
    }
    return true
}
